package edu.nju.desserthouse.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nju.edu.desserthouse.model.Bonus;
import nju.edu.desserthouse.model.Goods;
import nju.edu.desserthouse.model.Vip;
import edu.nju.desserthouse.dao.BonusDao;
import edu.nju.desserthouse.dao.GoodsDao;
import edu.nju.desserthouse.dao.VipDao;

/**
 * Servlet implementation class BuyGoodsServlet
 */
@WebServlet("/seedetail.goods")
public class SeeGoodsServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	@EJB
	GoodsDao goodsDao;
	@EJB
	VipDao vipDao;
	@EJB
	BonusDao bonusDao;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SeeGoodsServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute (request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute (request, response);
	}
	
	public void execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		String goods_id = req.getParameter("goods_id");
		req.getSession().setAttribute("goods_id", goods_id);
		
		Goods goods = goodsDao.find("id", goods_id);
		
		long vip_id = Long.valueOf(req.getSession().getAttribute("vip_id").toString());
		
		
		Vip vip = vipDao.find("id", Long.toString(vip_id));
		String level = Integer.toString(vip.getLevel());
		Bonus bonus = bonusDao.find("level", level);
		double discount = bonus.getDiscount();
		double price = goods.getPrice();
		
		price *= discount;
		
		req.getSession().setAttribute("goods_id",goods.getId());
		req.getSession().setAttribute("goods_name",goods.getName());
		req.getSession().setAttribute("goods_num", goods.getNum());
		req.getSession().setAttribute("goods_price", goods.getPrice());
		req.getSession().setAttribute("actual_price", price);
		resp.sendRedirect("/desserthouseWEB/goods/buygoods.jsp");
	}

}
